package jack.com.servicekeep.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import jack.com.servicekeep.R;
import jack.com.servicekeep.utils.AppUtil;
import jack.com.servicekeep.utils.SystemUtil;


public class MyAccessibilityService extends AccessibilityService {

    final String TAG = "yanjun";

    private MediaPlayer mp;
    private Vibrator vibrator;

    private Timer heartBeatTimer = new Timer();
    private Timer accessibilityTimer = new Timer();

    private PowerManager.WakeLock mWakeLock;

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.e(TAG, "onServiceConnected");
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

        heartBeatTimer.schedule(heaterBeatTask, 0, 90000);
        accessibilityTimer.schedule(accessibilityTask, 0, 3000);

        if (null == mWakeLock) {
            PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
            mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "dingzixue:service");
            if (null != mWakeLock) {
                mWakeLock.acquire();
            }
        }

        //showFloatingWindow();
        //mHandler.postDelayed(sRunnable, 3000);
    }

    private String phoneId;
    private String phoneNumber;
    private int state;
    private int battery;
    private int phoneState;

    private boolean flagCancelReport = false;

    private Handler.Callback mCallback = new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    checkIsForbidSetting();
                break;
                case 2:
                    String school = AppUtil.getSchoolName(getApplicationContext());
                    Toast.makeText(getApplicationContext(), "钉钉尚未加入\""+school+"\"", Toast.LENGTH_SHORT).show();
                break;
            }
            return true;
        }
    };

    private Handler mHandler = new WeakRefHandler(mCallback);

    private final Runnable sRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.postDelayed(sRunnable, 500);
        }
    };

    TimerTask heaterBeatTask = new TimerTask() {

        @Override
        public void run() {
            int dingState = AppUtil.getDingState(getApplicationContext());
            if (dingState == 0) {
                 Log.d("yanjun", "heaterBeatTask Ding state = " + dingState + ", return");
                 return;
            }

            if(dingState == 2 ){
                int cancelIsReport =  AppUtil.getCancelIsReport(getApplicationContext());
                if(cancelIsReport == 1){
                    Log.d("yanjun", "Ding state = " + dingState + " cancelIsReport = " + cancelIsReport + " return");
                    return;
                }else{
                    flagCancelReport = true;
                }
            }
            doHeartBeat();
        }
    };

    TimerTask accessibilityTask = new TimerTask() {

        @Override
        public void run() {

            mHandler.sendEmptyMessage(1);

            Log.d("yanjun", "windows size = "+getWindows().size());

            try {

            for(AccessibilityWindowInfo info : getWindows()){
                AccessibilityNodeInfo root = info.getRoot();
                //Log.d("yanjun", (root == null ? "root = null" : "package = " + root.getPackageName() + ( root != null ? " ClassName = " +root.getClassName() : "")));
                if(root != null) {
                    if (root.getPackageName().equals("com.alibaba.android.rimet")) {
                        try {
                            checkPerformView(root);
                        }catch (Exception e){
                            Log.e("yanjun", e.toString());
                        }
                    }else if (root.getPackageName().equals("com.android.settings")) {
                        checkSetting(root);
                    }else if(root.getPackageName().equals("com.huawei.android.internal.app")){
                        checkLauncherSelectDialog(root);
                    }else if(root.getPackageName().equals("com.huawei.systemmanager")){
                        if(AppUtil.getAutoSettingsFlag(getApplicationContext()) == 1 && !flagSettingLauncherAndNoticeDone) {
                            checkSetting(root);
                            return;
                        }
                        checkClean(root);
                    }else if(root.getPackageName().equals("com.android.systemui")){
                        if(AppUtil.getAutoSettingsFlag(getApplicationContext()) == 1) {
                            checkSetting(root);
                        }
                        if(AppUtil.getAllowLearnState(getApplicationContext()) == false) {
                            checkCleanRecent(root);
                        }
                    }else if(root.getPackageName().equals("com.huawei.android.hwouc")){
                        checkUpdateSystemDialog(root);
                        checkUpdateSystemView(root);
                    }
                }
            }
            }catch (Exception e){
                Log.d(TAG, e.toString());
            }
        }
    };

    private void doHeartBeat(){
        BatteryManager manager = (BatteryManager) getSystemService(BATTERY_SERVICE);
        battery = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

        phoneId = AppUtil.getDeviceUUID(getApplicationContext());
        phoneNumber = AppUtil.getPhoneNumber2(getApplicationContext());

        boolean isPlaying = AppUtil.isPlay(getApplicationContext());
        state = isPlaying ? 1 : 0;

        phoneState = AppUtil.getDingState(getApplicationContext());

        final JSONObject requestMap = new JSONObject();
        try {
            requestMap.put("phoneId", AppUtil.getDeviceUUID(getApplicationContext()));
            requestMap.put("state", state);
            requestMap.put("secretKey", "YUEksdi6775KNs94STNBXk32");
            requestMap.put("phoneNumber", "13888888888");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
//                    AppUtil.heartbeat2("http://" + host_port + "/heart.go/?", requestMap.toString());
                String data = AppUtil.heartbeat2(phoneId, state, phoneNumber, battery, phoneState);
                parseData(data);
            }
        });
        thread.start();
    }

    private void setVolume(Context context) {
//        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !notificationManager.isNotificationPolicyAccessGranted()) {
//            startActivity(new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS));
//            return;
//        }

        AudioManager audioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 12, AudioManager.FLAG_PLAY_SOUND);
        //audioManager.setStreamVolume(AudioManager.STREAM_ALARM, 12, AudioManager.FLAG_VIBRATE);
        //audioManager.setStreamVolume(AudioManager.STREAM_RING, 12, AudioManager.FLAG_VIBRATE);
    }

    //暂停
    public void pause() {
        if (mp != null) {
            mp.stop();
            mp = null;
        }

        if (vibrator != null) {
            vibrator.cancel();
        }
    }

    public void playSound(int soundIndex){

        pause();

        int res_id = getSoundResId(soundIndex);
        if (res_id != -1) {
            setVolume(getApplicationContext());

            mp = MediaPlayer.create(this, res_id);
            mp.start();
        }

        if (vibrator != null) {
            vibrator.cancel();
            vibrator.vibrate(getVibratorTime(soundIndex));
        }
    }

    private static void print(String tag){
        Log.d("yanjun", tag + " pid=" + android.os.Process.myPid());
        Log.d("yanjun", tag + " tid=" + android.os.Process.myTid());
        Log.d("yanjun", tag + " uid=" + android.os.Process.myUid());
    }

    private int getVibratorTime(int soundIndex){
        switch (soundIndex){
            case 0:
                return 8000;
            case 1:
                return 3000;
            case 2:
                return 7000;
            case 3:
                return 12000;
            case 4:
                return 12000;
            case 5:
                return 8000;
            case 6:
                return 6000;
            case 7:
                return 2000;
        }
        return 2000;
    }

    private int getSoundResId(int soundIndex){
        switch (soundIndex){
            case 0:
                return R.raw.sound_0;
            case 1:
                return R.raw.sound_1;
            case 2:
                return R.raw.sound_2;
            case 3:
                return R.raw.sound_3;
            case 4:
                return R.raw.sound_4;
            case 5:
                return R.raw.sound_5;
            case 6:
                return R.raw.sound_6;
            case 7:
                return R.raw.sound_7;
        }
        return -1;
    }

    public void parseData(String jsonStr){
        Log.d("yanjun", "respnse data: " + jsonStr);

        if(jsonStr.isEmpty()){
            return;
        }

        if(AppUtil.getDingState(getApplicationContext()) == 2 && flagCancelReport){
            AppUtil.cancelReported(getApplicationContext());
            flagCancelReport = false;
        }

        Gson gson = new Gson();
        HeaterResponseData data = new HeaterResponseData();

        try {
            data = gson.fromJson(jsonStr, HeaterResponseData.class);
        }catch (Exception e) {

        }

        if(data.isAlert == 1){
            playSound(data.videoType);
        }

        if(data.isExit == 1){
            performGlobalAction(GLOBAL_ACTION_HOME);
        }

        if(data.allow == false){
            if(AppUtil.getAllowLearnState(getApplicationContext()) == true){
                performGlobalAction(GLOBAL_ACTION_RECENTS);
            }else{
                performGlobalAction(GLOBAL_ACTION_HOME);
            }
        }
        AppUtil.setAllowLearnState(getApplicationContext(), data.allow);
    }

    private void checkPerformView(AccessibilityNodeInfo rootInActiveWindow){

        if(AppUtil.getUpdateDingState(getApplicationContext()) == 1){
            checkUpdateDingPerformView(rootInActiveWindow);
        }
        else if(AppUtil.getPunchClockState(getApplicationContext()) == 1){
            checkPunchClockPerformView(rootInActiveWindow);
        }
        else{
            checkLearnPerformView(rootInActiveWindow);
        }
    }

    private int checkUpdateCount = 0;

    private boolean isDingDingHome(AccessibilityNodeInfo rootInActiveWindow){
        List<AccessibilityNodeInfo> nodeInfoList;
        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/bottom_tab");
        if(nodeInfoList != null && nodeInfoList.size() > 0){
            return true;
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/home_app_recycler_view");
        if(nodeInfoList != null && nodeInfoList.size() > 0){
            return true;
        }
        return false;
    }

    private boolean isYunKeTangHome(AccessibilityNodeInfo rootInActiveWindow) {
        List<AccessibilityNodeInfo> nodeInfoList;
        AccessibilityNodeInfo nodeInfo;

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/menu_current_company");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            nodeInfo = nodeInfoList.get(0);
            String school = AppUtil.getSchoolName(getApplicationContext());
            if(!nodeInfo.getText().equals(school)){
                mHandler.sendEmptyMessage(2);
                return true;
            }
            performOperation(PerformType.TOALL, rootInActiveWindow);
            AppUtil.sleep(1500);
            return true;
        }
        return false;
    }

    private void checkUpdateDingPerformView(AccessibilityNodeInfo rootInActiveWindow) {
        List<AccessibilityNodeInfo> nodeInfoList;

        if(isHaveTextInWindow(rootInActiveWindow, "发现新版本", 1)){
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/button1");
            if(nodeInfoList != null && nodeInfoList.size() > 0){
                nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                Log.d("yanjun", "performAction : Click dingding setting update");
                AppUtil.setUpdateDingState(getApplicationContext(), 0);
                return;
            }
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/setting_check_new_version");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            flagDelay = 1;
            checkUpdateCount++;
            if(checkUpdateCount > 1){
                flagDelay = 0;
                AppUtil.setUpdateDingState(getApplicationContext(), 0);
            }
            Log.d("yanjun", "performAction : Click dingding setting check new version");
            return;
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/setting_about");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            checkUpdateCount = 0;
            Log.d("yanjun", "performAction : Click dingding setting about");
            return;
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/my_page_setting");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            Log.d("yanjun", "performAction : Click dingding setting");
            return;
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/setting");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            Log.d("yanjun", "performAction : Click dingding setting");
            return;
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/fl_avatar");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            Log.d("yanjun", "performAction : Click my avatar");
            return;
        }

        if(isDingDingHome(rootInActiveWindow)){
            performOperation(PerformType.MsgTab, rootInActiveWindow);
            return;
        }

        checkAndCloseOrBack(rootInActiveWindow);
    }

    private void checkPunchClockPerformView(AccessibilityNodeInfo rootInActiveWindow){
        List<AccessibilityNodeInfo> nodeInfoList ;
        AccessibilityNodeInfo nodeInfo;

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/webview_frame");
        if (nodeInfoList != null && nodeInfoList.size() > 0) {
            nodeInfo = findTextInNodeInfo(nodeInfoList.get(0), "上班打卡");
            if(nodeInfo == null){
                Log.d("yanjun", "Not da ka, return");
                checkAndCloseOrBack(rootInActiveWindow);
                return;
            }
            nodeInfo = nodeInfoList.get(0).getChild(0).getChild(0).getChild(0).getChild(1).getChild(0).getChild(0).getChild(1);
            nodeInfo = nodeInfo.getChild(nodeInfo.getChildCount()-1).getChild(0).getChild(2);
            Log.d("yanjun", "Do da ka");
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            flagDelay = 2;
            AppUtil.setPunchClockState(getApplicationContext(), 0);
            return;
        }else{
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/h5_pc_container");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                if(isHaveTextInWindow(rootInActiveWindow,"[0-9]{2}:[0-9]{2}:[0-9]{2}",2)){
                    click(360, 870);
                    flagDelay = 3;
                    Log.d("yanjun", "Do new da ka");
                    AppUtil.setPunchClockState(getApplicationContext(), 0);
                    return;
                }
            }
        }

        if(isYunKeTangHome(rootInActiveWindow)){
            performOperation(PerformType.PunchClock, rootInActiveWindow);
            return;
        }

        if(isDingDingHome(rootInActiveWindow)){
            performOperation(PerformType.WorkTab, rootInActiveWindow);
            return;
        }

        checkAndCloseOrBack(rootInActiveWindow);
    }

    private enum PerformType{WorkTab, YunKeTang, RecentCourse, GoOnLearning, PlayVideo, PunchClock, LearnCenter, RecentCourse_2, MsgTab, MyAvatar, TOALL}
    private int flagDelay = 0;

    private void checkLearnPerformView(AccessibilityNodeInfo rootInActiveWindow){
        List<AccessibilityNodeInfo> nodeInfoList  = null;

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/title_bar_name");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            AccessibilityNodeInfo menu = nodeInfoList.get(0);
            CharSequence title = menu.getText();
            if (title != null && title.toString().equals("视频详情")) {
                performOperation(PerformType.PlayVideo, rootInActiveWindow);
                return;
            }
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/title_bar_name");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            AccessibilityNodeInfo menu = nodeInfoList.get(0);
            CharSequence title = menu.getText();
            if (title != null && title.toString().equals("培训详情")) {
                performOperation(PerformType.GoOnLearning, rootInActiveWindow);
                return;
            }
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/title_bar_name");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            AccessibilityNodeInfo menu = nodeInfoList.get(0);
            CharSequence title = menu.getText();
            if (title != null && title.toString().equals("学习中心")) {
                performOperation(PerformType.LearnCenter, rootInActiveWindow);
                return;
            }
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/title_bar_name");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            AccessibilityNodeInfo menu = nodeInfoList.get(0);
            CharSequence title = menu.getText();
            if (title != null && title.toString().equals("首页")) {
                nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/h5_pc_container");
                if(nodeInfoList != null && nodeInfoList.size() > 0){
                    performOperation(PerformType.RecentCourse_2, rootInActiveWindow);
                    //if(performOperation(PerformType.RecentCourse, rootInActiveWindow) == false){
                    //    performOperation(PerformType.RecentCourse_2, rootInActiveWindow);
                    //}
                    return;
                }
            }
        }

        if(isYunKeTangHome(rootInActiveWindow)){
            performOperation(PerformType.YunKeTang, rootInActiveWindow);
            return;
        }

        if(isDingDingHome(rootInActiveWindow)) {
            performOperation(PerformType.WorkTab, rootInActiveWindow);
            return;
        }

        checkAndCloseOrBack(rootInActiveWindow);
    }

    private void checkAndCloseOrBack(AccessibilityNodeInfo rootInActiveWindow){
        List<AccessibilityNodeInfo> nodeInfoList  = null;

        Log.d("yanjun", "flagDelay=" + flagDelay);
        if(flagDelay > 0 && flagDelay < 4){
            Log.d("yanjun", "Waiting load , return");
            flagDelay++;
            return;
        }else{
            flagDelay = 0;
        }

        if(isHaveTextInWindow(rootInActiveWindow, "是否去打外勤卡", 1)){
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/button2");
            if(nodeInfoList != null && nodeInfoList.size() > 0){
                nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                return;
            }
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/close_layout");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            Log.d("yanjun", "Not learning view, Do Close");
            nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }else{
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/login_pwd_rl");
            if(nodeInfoList != null && nodeInfoList.size() > 0){
                return;
            }
            if(isHaveTextInWindow(rootInActiveWindow, "欢迎使用钉钉", 0)){
                return;
            }
            if(isHaveTextInWindow(rootInActiveWindow, "请输入手机号", 0)){
                return;
            }
            if(isHaveTextInWindow(rootInActiveWindow, "现在能接收短信吗", 1)){
                return;
            }
            if(isHaveTextInWindow(rootInActiveWindow, "验证码已发送至手机", 0)){
                return;
            }
            if(isHaveTextInWindow(rootInActiveWindow, "发起帐号申诉", 0)){
                return;
            }
            if(isHaveTextInWindow(rootInActiveWindow, "确认手机号", 0)){
                return;
            }
            if(isHaveTextInWindow(rootInActiveWindow, "激活码页", 0)){
                return;
            }
            if(isHaveTextInWindow(rootInActiveWindow, "为确保帐号安全", 1)){
                return;
            }

            Log.d("yanjun", "Not learning view, Do Back");
            performGlobalAction(GLOBAL_ACTION_BACK);
        }
    }

    private boolean closeMiniProgram(AccessibilityNodeInfo rootInActiveWindow){
        List<AccessibilityNodeInfo> nodeInfoList ;

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/close_layout");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            Log.d("yanjun", "Close MiniProgram");
            nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            return true;
        }
        return false;
    }

    private boolean isHaveTextInWindow(AccessibilityNodeInfo root, String text, int type){
        AccessibilityNodeInfo resultNode;
        resultNode = findTextInNodeInfo(root, text, type);
        Log.d("yanjun", "isHaveTextInWindow text="+text + " type=" + type + " " + (resultNode == null ? false : true));
        if(resultNode != null){
            return true;
        }
        return false;
    }

    private boolean isFirstEnterVideoView = false;
    private int     mBlockTimes;
    private boolean performOperation(PerformType  type, AccessibilityNodeInfo rootInActiveWindow ){
        List<AccessibilityNodeInfo> nodeInfoList ;
        AccessibilityNodeInfo nodeInfo;

        Log.d("yanjun", "performOperation type = " + type);

        if(type == PerformType.WorkTab){
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/home_bottom_tab_button_work");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                try {
                    Log.d("yanjun", "performAction : Work Tab");
                    nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    flagDelay = 1;
                }catch (Exception e){
                    Log.d("yanjun", "find Work Tab error : "+  e);
                }
            }else {
                nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/home_app_recycler_view");
                if(nodeInfoList != null && nodeInfoList.size() > 0){
                    try {
                        Log.d("yanjun", "performAction : Work Tab 2");
                        nodeInfoList.get(0).getChild(2).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        flagDelay = 1;
                    }catch (Exception e){
                        Log.d("yanjun", "find Work Tab 2 error : "+  e);
                    }
                }
            }

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else if(type == PerformType.MsgTab){
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/home_bottom_tab_button_message");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                try {
                    Log.d("yanjun", "performAction : Msg Tab");
                    nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    flagDelay = 1;
                }catch (Exception e){
                    Log.d("yanjun", "find Msg Tab error : "+  e);
                }
            }else{
                nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/home_app_recycler_view");
                if(nodeInfoList != null && nodeInfoList.size() > 0){
                    try {
                        Log.d("yanjun", "performAction : Msg Tab 2");
                        nodeInfoList.get(0).getChild(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        flagDelay = 1;
                    }catch (Exception e){
                        Log.d("yanjun", "find Msg Tab 2 error : "+  e);
                    }
                }
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else if(type == PerformType.YunKeTang){

            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/h5_pc_container");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                try {
                    nodeInfo = findTextInNodeInfo(nodeInfoList.get(0), "云课堂");
                    if(nodeInfo != null){
                        Log.d("yanjun", "performAction : Yun Ke Tang");
                        //nodeInfo.getParent().getParent().getChild(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.left + 5, rect.top - 10);
                        flagDelay = 1;
                        mBlockTimes = 0;
                    }
                } catch (Exception e) {
                    Log.d("yanjun", "find Yun Ke Tang error : "+  e);
                }
            }

            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else if(type == PerformType.RecentCourse){
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/h5_pc_container");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                nodeInfo = findTextInNodeInfo(nodeInfoList.get(0), "学习任务");
                if (nodeInfo != null) {
                    Rect inScreen = new Rect();
                    nodeInfo.getBoundsInScreen(inScreen);
                    Log.d("yanjun", "Click x = " + inScreen.right + " y = " + (inScreen.bottom + (inScreen.right - inScreen.left) * 2));
                    Log.d("yanjun", "performAction : Recent Course");
                    //click(inScreen.right, inScreen.bottom + (inScreen.right - inScreen.left)*2);
                    click(162, inScreen.bottom + (inScreen.right - inScreen.left) * 2);
                    flagDelay = 0;
                } else {
                    return false;
                }
            }else{
                return false;
            }

            try {
                Thread.sleep(3500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else if(type == PerformType.RecentCourse_2){
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/h5_pc_container");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                nodeInfo = findTextInNodeInfo(nodeInfoList.get(0), "课程列表");
                if(nodeInfo != null){
                    boolean ret = nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    Log.d("yanjun", "performAction : Recent Course_2 action=" + ret);
                    return true;
                }
            }

            mBlockTimes++;

            if(mBlockTimes >= 5){
                closeMiniProgram(rootInActiveWindow);
                mBlockTimes = 0;
            }

            try {
                Thread.sleep(3500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else if(type == PerformType.LearnCenter){
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/h5_pc_container");
            mListNodeInfo.clear();

            String code = AppUtil.getCourseCode(getApplicationContext());

            findAllTextInNodeInfo(nodeInfoList.get(0), "必修", 0);

            Log.d("yanjun", "List size = "+ mListNodeInfo.size() + " code="+code);

            if (mListNodeInfo.size() > 0) {
                for (int i = 0; i < mListNodeInfo.size(); i++) {
                    nodeInfo = mListNodeInfo.get(i);
                    int count = nodeInfo.getParent().getParent().getChildCount();
                    String title = nodeInfo.getParent().getParent().getParent().getChild(0).getText().toString();
                    Log.d("yanjun", " @@ title" + title + "  count=" + count);
                    boolean isMatch = title.contains(code);
                    if (count == 2 && isMatch) {
                        //nodeInfo.getParent().getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        if(rect.top > 1350){
                            Log.d("yanjun", "Do LearnCenter goon moveup top=" + rect.top);
                            moveUpLittle();
                        }else if(rect.top < 390){
                            Log.d("yanjun", "Do LearnCenter move down top=" + rect.top);
                            moveDown();
                        }else{
                            Log.d("yanjun", "Do LearnCenter Click " + i);
                            click(rect.right, rect.top);
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        return true;
                    }
                }
                moveUp();
            }
        }else if(type == PerformType.GoOnLearning){

            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/h5_pc_container");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                try {
                    Rect rect = new Rect();
                    nodeInfoList.get(0).getBoundsInScreen(rect);
                    Log.d("yanjun", "Click x = "+ (rect.right - rect.left)/ 2 + " y = "+ (rect.bottom - 16 - 36));
                    Log.d("yanjun", "performAction : Goon Learning");
                    click((rect.right - rect.left)/ 2, rect.bottom - 16 - 36);
                    isFirstEnterVideoView = true;
                }catch (Exception e){
                    Log.d("yanjun", "find Goon Learning error : "+  e);
                }
            }

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else if(type == PerformType.PlayVideo){
            if(AppUtil.isPlay(getApplicationContext())){
                isFirstEnterVideoView = false;
                return true;
            }

            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/video_controller_current_time");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                CharSequence text = nodeInfoList.get(0).getText();
                if(text != null && text.toString().equals("00:00") && !isFirstEnterVideoView){
                    closeMiniProgram(rootInActiveWindow);
                    return true;
                }
                nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/video_controller_play_btn");
                if (nodeInfoList != null && nodeInfoList.size() > 0) {
                    nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
            }else{
                click(360, 350);
            }
        }else if(type == PerformType.PunchClock){
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/h5_pc_container");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                try {
                    nodeInfo = findTextInNodeInfo(nodeInfoList.get(0), "考勤打卡", 0);
                    if(nodeInfo != null){
                        Log.d("yanjun", "performAction : Da ka");
                        flagDelay = 1;
                        nodeInfo.getParent().getParent().getChild(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                } catch (Exception e) {
                    Log.d("yanjun", "find Da ka error : "+  e);
                }
            }
            AppUtil.sleep(4000);
        }else if(type == PerformType.TOALL){
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.alibaba.android.rimet:id/h5_pc_container");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                try {
                    nodeInfo = findTextInNodeInfo(nodeInfoList.get(0), "全员", 0);
                    if (nodeInfo != null) {
                        Log.d("yanjun", "performAction : To All");
                        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }catch (Exception e) {
                    Log.d("yanjun", "find ToAll error : "+  e);
                }
            }
        }
        return true;
    }

    private boolean isDingZiXueSetting = false;
    private List accessData = new ArrayList();
    {
        //accessData.add(new AccessibilityData());
    }

    private boolean doAccessById( AccessibilityNodeInfo rootInActiveWindow, AccessibilityData accessData){
        List<AccessibilityNodeInfo> nodeInfoList ;
        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId(accessData.getSearchContent());
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            Log.d("yanjun", "performAction : " + accessData.toString());
            return true;
        }
        return false;
    }

    private AccessibilityNodeInfo findNodeById(AccessibilityNodeInfo rootInActiveWindow, String id){
        List<AccessibilityNodeInfo> nodeInfoList ;
        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId(id);
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            return nodeInfoList.get(0);
        }
        return null;
    }


    private void doAutoSettingsAbout(AccessibilityNodeInfo rootView){
        AccessibilityNodeInfo nodeInfo;

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null){
            if(nodeInfo.getText().equals("开发人员选项")) {
                if((nodeInfo = findTextInNodeInfo(rootView, "锁屏")) != null) {
                    if(nodeInfo.getParent().getChild(2).isChecked()){
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.right, rect.bottom);
                        AppUtil.sleep(500);
                    }
                }
                AppUtil.sleep(300);

                if((nodeInfo = findTextInNodeInfo(rootView, "自动系统更新")) != null) {
                    if(nodeInfo.getParent().getChild(1).isChecked()){
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.right, rect.bottom);
                        AppUtil.sleep(500);
                    }
                }
                AppUtil.sleep(300);

                if((nodeInfo = findTextInNodeInfo(rootView, "开发者选项")) != null) {
                    if(nodeInfo.getParent().getChild(1).isChecked()){
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.right, rect.bottom);
                    }
                }
                flagSettingAboutDone = true;
                performGlobalAction(GLOBAL_ACTION_BACK);
                AppUtil.sleep(500);
                performGlobalAction(GLOBAL_ACTION_BACK);
                return;
            }
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null) {
            if (nodeInfo.getText().equals("关于手机")) {
                if((nodeInfo = findTextInNodeInfo(rootView, "版本号")) != null) {
                    for(int i=0; i<8; i++) {
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.right, rect.bottom);

                        AppUtil.sleep(300);
                    }
                    performGlobalAction(GLOBAL_ACTION_BACK);
                }
                return;
            }
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null){
            if(nodeInfo.getText().equals("系统")) {
                if((nodeInfo = findTextInNodeInfo(rootView, "开发人员选项")) != null){
                    Rect rect = new Rect();
                    nodeInfo.getBoundsInScreen(rect);
                    click(rect.right, rect.bottom);
                }else{
                    if((nodeInfo = findTextInNodeInfo(rootView, "关于手机")) != null) {
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.right, rect.bottom);
                    }
                }
                return;
            }
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null){
            if(nodeInfo.getText().equals("设置")){
                if((nodeInfo = findTextInNodeInfo(rootView, "系统")) != null){
                    Rect rect = new Rect();
                    nodeInfo.getBoundsInScreen(rect);
                    click(rect.right, rect.bottom);
                }else{
                    moveUp();
                }
            }
        }
    }

    private void doAutoSettingsDisplay(AccessibilityNodeInfo rootView){
        AccessibilityNodeInfo nodeInfo;

        if(findNodeById(rootView, "android:id/select_dialog_listview") != null){
            if((nodeInfo = findTextInNodeInfo(rootView, "永不")) != null){
                nodeInfo.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                performGlobalAction(GLOBAL_ACTION_BACK);
                flagSettingDisplayDone = true;
            }
            return;
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null){
            if(nodeInfo.getText().equals("显示")){
                if((nodeInfo = findNodeById(rootView, "com.android.settings:id/toggle")) != null){
                    if(!nodeInfo.isChecked()){
                        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }

                if((nodeInfo = findNodeById(rootView, "android:id/switch_widget")) != null){
                    if(!nodeInfo.isChecked()){
                        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }

                if((nodeInfo = findTextInNodeInfo(rootView, "休眠")) != null){
                    Rect rect = new Rect();
                    nodeInfo.getBoundsInScreen(rect);
                    click(rect.right, rect.bottom);
                }
                return;
            }
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null){
            if(nodeInfo.getText().equals("设置")){
                if((nodeInfo = findTextInNodeInfo(rootView, "显示")) != null){
                    Rect rect = new Rect();
                    nodeInfo.getBoundsInScreen(rect);
                    click(rect.right, rect.bottom);
                }
            }
        }
    }

    private void doAutoSettingsNotice(AccessibilityNodeInfo rootView){
        AccessibilityNodeInfo nodeInfo;

        if((nodeInfo = findTextInNodeInfo(rootView, "更换")) != null){
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            flagSettingLauncherAndNoticeDone = true;
            performGlobalAction(GLOBAL_ACTION_RECENTS);
            return;
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null) {
            if (nodeInfo.getText().equals("桌面")) {
                if((nodeInfo = findTextInNodeInfo(rootView, "钉自学")) != null){
                    if(nodeInfo.getParent().getChild(1).isChecked()){
                        flagSettingLauncherAndNoticeDone = true;
                        performGlobalAction(GLOBAL_ACTION_RECENTS);
                    }else {
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.right, rect.bottom);
                    }
                }
                return;
            }
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null) {
            if (nodeInfo.getText().equals("默认应用")) {
                if((nodeInfo = findTextInNodeInfo(rootView, "桌面")) != null){
                    Rect rect = new Rect();
                    nodeInfo.getBoundsInScreen(rect);
                    click(rect.right, rect.bottom);
                }
                return;
            }
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null){
            if(nodeInfo.getText().equals("批量管理")){
                if(flagSettingNoticeDone){
                    performGlobalAction(GLOBAL_ACTION_BACK);
                    return;
                }
                if((nodeInfo = findNodeById(rootView, "com.huawei.systemmanager:id/allpackage_manager_switch")) != null){
                    if(nodeInfo.isChecked()){
                        nodeInfo.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }else{
                        nodeInfo.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        nodeInfo.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }

                if((nodeInfo = findTextInNodeInfo(rootView, "钉钉")) != null){
                    if(!nodeInfo.getParent().getParent().getParent().getChild(1).getChild(0).isChecked()){
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.right, rect.bottom);
                    }
                }

                AppUtil.sleep(500);

                if((nodeInfo = findTextInNodeInfo(rootView, "钉自学")) != null){
                    if(!nodeInfo.getParent().getParent().getParent().getChild(1).getChild(0).isChecked()){
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.right, rect.bottom);
                    }
                }
                flagSettingNoticeDone = true;
                return;
            }
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null){
            if(nodeInfo.getText().equals("通知管理")){
                if(flagSettingNoticeDone){
                    performGlobalAction(GLOBAL_ACTION_BACK);
                    return;
                }
                if((nodeInfo = findNodeById(rootView, "com.huawei.systemmanager:id/manager_channel_mainarrowlayout")) != null){
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
                return;
            }
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null){
            if(nodeInfo.getText().equals("应用和通知")){
                if(!flagSettingNoticeDone){
                    if((nodeInfo = findTextInNodeInfo(rootView, "通知管理")) != null){
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.right, rect.bottom);
                    }
                }else {
                    if((nodeInfo = findTextInNodeInfo(rootView, "默认应用")) != null){
                        Rect rect = new Rect();
                        nodeInfo.getBoundsInScreen(rect);
                        click(rect.right, rect.bottom);
                    }
                }
                return;
            }
        }

        if((nodeInfo = findNodeById(rootView, "android:id/action_bar_title")) != null){
            if(nodeInfo.getText().equals("设置")){
                if((nodeInfo = findTextInNodeInfo(rootView, "应用和通知")) != null){
                    Rect rect = new Rect();
                    nodeInfo.getBoundsInScreen(rect);
                    click(rect.right, rect.bottom);
                }
            }
        }
    }

    private boolean flagSettingAboutDone = false;
    private boolean flagSettingDisplayDone = false;
    private boolean flagSettingLauncherAndNoticeDone = false;
    private boolean flagSettingNoticeDone = false;

    private void checkSetting(AccessibilityNodeInfo rootInActiveWindow) {
        List<AccessibilityNodeInfo> nodeInfoList ;

        if(AppUtil.getAutoSettingStart(getApplicationContext()) == 1) {
            flagSettingAboutDone = false;
            flagSettingDisplayDone = false;
            flagSettingLauncherAndNoticeDone = false;
            AppUtil.setAutoSettingsStart(getApplicationContext(), 0);
        }

        if(AppUtil.getAutoSettingsFlag(getApplicationContext()) == 1) {
            if(SystemUtil.getSystemModel().equals("AUM-AL20")){

                if(!flagSettingAboutDone) {
                    doAutoSettingsAbout(rootInActiveWindow);
                    return;
                }

                if(!flagSettingDisplayDone) {
                    doAutoSettingsDisplay(rootInActiveWindow);
                    return;
                }

                if(!flagSettingLauncherAndNoticeDone) {
                    doAutoSettingsNotice(rootInActiveWindow);
                    return;
                }

                AccessibilityNodeInfo nodeInfo;
                if((nodeInfo = findNodeById(rootInActiveWindow, "com.android.systemui:id/recent_igmbutton_clear_all")) != null){
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    AppUtil.setAutoSettingsFlag(getApplicationContext(), 0);
                    return;
                }

            }
        }

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/action_bar_title");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            AccessibilityNodeInfo menu = nodeInfoList.get(0);
            CharSequence title = menu.getText();
            if (title == null){
                return;
            }
            Log.d("yanjun", "checkSetting title" + title);
            if(title.toString().equals("钉钉按键精灵") || title.toString().equals("无障碍")) {
                performGlobalAction(GLOBAL_ACTION_BACK);
                isDingZiXueSetting = false;
            }else if(title.toString().equals("应用信息") || title.toString().equals("配置应用") || title.toString().equals("主屏幕应用")){
                if(AppUtil.getDingState(getApplicationContext()) == 2){
                    changeLauncherToHuawei(rootInActiveWindow, title.toString());
                }
            }else{
                isDingZiXueSetting = false;
            }
        }
    }

    private void checkCleanRecent(AccessibilityNodeInfo rootInActiveWindow) {
        AccessibilityNodeInfo nodeInfo;
        if((nodeInfo = findNodeById(rootInActiveWindow, "com.android.systemui:id/recent_igmbutton_clear_all")) != null){
            Log.d("yanjun", "Do clean all recent task");
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            return;
        }
    }

    private void checkClean(AccessibilityNodeInfo rootInActiveWindow) {
        List<AccessibilityNodeInfo> nodeInfoList;
        AccessibilityNodeInfo nodeInfo;

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/action_bar_title");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            AccessibilityNodeInfo menu = nodeInfoList.get(0);
            CharSequence title = menu.getText();
            if (title == null){
                return;
            }
            Log.d("yanjun", "checkClean title" + title);
            if(title.toString().equals("钉钉")) {
                nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.huawei.systemmanager:id/delete");
                if(nodeInfoList != null && nodeInfoList.size() > 0) {
                    AccessibilityNodeInfo node = nodeInfoList.get(0);
                    node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    Log.d("yanjun", "performAction : Do Clean DingDing");
                    performGlobalAction(GLOBAL_ACTION_HOME);
                }
            }else if(title.toString().equals("应用占用详情")){
                nodeInfo = findTextInNodeInfo(rootInActiveWindow, "钉钉");
                if(nodeInfo != null){
                    nodeInfo.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    Log.d("yanjun", "performAction : Enter Clean DingDing");
                }
            }else if(title.toString().equals("清理加速")){

                nodeInfo = findTextInNodeInfo(rootInActiveWindow, "查找占用空间较大的应用");
                if(nodeInfo != null){
                    Rect rect = new Rect();
                    nodeInfo.getBoundsInScreen(rect);
                    click(rect.right, rect.bottom);
                    Log.d("yanjun", "performAction : Find Clean APP List " + rect.right + " " + rect.bottom);
                }else{
                    performGlobalAction(GLOBAL_ACTION_HOME);
                    Log.d("yanjun", "performAction : Needn't clean, back");
                }
            }else{
                Log.d("yanjun", "CheckClean do back" + title);
                performGlobalAction(GLOBAL_ACTION_BACK);
            }
        }
    }

    private void changeLauncherToHuawei(AccessibilityNodeInfo rootInActiveWindow, String title){
        List<AccessibilityNodeInfo> nodeInfoList ;
        Log.d("yanjun", "changeLauncherToHuawei title" + title + " isDingZiXueSetting="+isDingZiXueSetting);
        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.android.settings:id/list");
        if(nodeInfoList == null || nodeInfoList.size() == 0) {
            return;
        }

        if(title.equals("应用信息")) {
            nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.android.settings:id/entity_header_title");
            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                AccessibilityNodeInfo menu = nodeInfoList.get(0);
                CharSequence text = menu.getText();
                if (text != null && text.toString().equals("钉自学")) {
                    nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.android.settings:id/list");
                    if (nodeInfoList != null && nodeInfoList.size() > 0) {
                        AccessibilityNodeInfo item = nodeInfoList.get(0).getChild(10);
                        item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        isDingZiXueSetting = true;
                        Log.d("yanjun", "1111111111-------");
                    }
                }
            }
        }else if(title.equals("配置应用")){
            Log.d("yanjun", "2222222");
            if(isDingZiXueSetting){
                AccessibilityNodeInfo item = nodeInfoList.get(0).getChild(2);
                item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                Log.d("yanjun", "222222222-------");
            }
        }else if(title.equals("主屏幕应用")){
            Log.d("yanjun", "333333333");
            if(isDingZiXueSetting){
                AccessibilityNodeInfo item = nodeInfoList.get(0).getChild(0);
                item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                performGlobalAction(GLOBAL_ACTION_HOME);
                isDingZiXueSetting = false;
                Log.d("yanjun", "333333333------");
            }
        }
    }

    private void checkLauncherSelectDialog(AccessibilityNodeInfo rootInActiveWindow) {
        List<AccessibilityNodeInfo> nodeInfoList ;

        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/alertTitle");
        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            AccessibilityNodeInfo menu = nodeInfoList.get(0);
            CharSequence title = menu.getText();
            Log.d("yanjun", "checkLauncherSelectDialog title = " + title);
            if (title != null && title.equals("使用以下方式打开")){

                try {
                    nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.huawei.android.internal.app:id/icon");
                    if(!nodeInfoList.get(0).isSelected()){
                        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.huawei.android.internal.app:id/resolver_grid");
                        //nodeInfoList.get(0).getChild(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                    Thread.sleep(300);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //click(144 + (264 - 144)/2,  1225 + (1305 - 1225)/2);
            }
        }
    }

    private void checkUpdateSystemDialog(AccessibilityNodeInfo rootInActiveWindow) {
        List<AccessibilityNodeInfo> nodeInfoList;
        nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/alertTitle");

        if(nodeInfoList != null && nodeInfoList.size() > 0) {
            AccessibilityNodeInfo info = nodeInfoList.get(0);
            CharSequence title = info.getText();
            Log.d("yanjun", "checkUpdateSystemDialog title = " + title);
            if (title != null && title.equals("系统更新")){
                try {
                    nodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/button3");
                    nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void checkUpdateSystemView(AccessibilityNodeInfo rootInActiveWindow) {
        List<AccessibilityNodeInfo> nodeInfoList;
        AccessibilityNodeInfo nodeInfo;
        nodeInfo = findTextInNodeInfo(rootInActiveWindow, "稍后提醒我", 0);

        if(nodeInfo != null ) {
            Log.d("yanjun", "checkUpdateSystemView title = " + nodeInfo.getText());
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }
    }

    public AccessibilityNodeInfo findTextInNodeInfo(AccessibilityNodeInfo node, String text) {
        return findTextInNodeInfo(node, text, 0);
    }

    // type  0: equals,  1:contains  2:matches
    public AccessibilityNodeInfo findTextInNodeInfo(AccessibilityNodeInfo node, String text, int type) {
        AccessibilityNodeInfo temp;
        if (node.getChildCount() == 0) {
            if (node.getText() != null) {
                if(type == 0){
                    if (text.equals(node.getText().toString())) {
                        return node;
                    }
                }else if(type == 1){
                    if (node.getText().toString().contains(text)) {
                        return node;
                    }
                }else if(type == 2){
                    if (node.getText().toString().matches(text)) {
                        return node;
                    }
                }
            }
        } else {
            for (int i = 0; i < node.getChildCount(); i++) {
                if (node.getChild(i) != null) {
                    temp = findTextInNodeInfo(node.getChild(i), text, type);
                    if(temp != null){
                        return temp;
                    }
                }
            }
        }
        return null;
    }

    private void moveUp() {
        Path path = new Path();
        path.moveTo(300, 1200);
        path.lineTo(300, 400);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        GestureDescription gesture = builder
                .addStroke(new GestureDescription.StrokeDescription(path, 50, 300))
                .build();
        this.dispatchGesture(gesture, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.i(TAG, "onCompleted: 滑动Up，手势完成");
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.i(TAG, "onCancelled: 失败");
            }
        }, null);
    }

    private void moveUpLittle() {
        Path path = new Path();
        path.moveTo(300, 1200);
        path.lineTo(300, 980);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        GestureDescription gesture = builder
                .addStroke(new GestureDescription.StrokeDescription(path, 50, 300))
                .build();
        this.dispatchGesture(gesture, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.i(TAG, "onCompleted: 滑动Up Little，手势完成");
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.i(TAG, "onCancelled: 失败");
            }
        }, null);
    }


    private void moveDown() {
        Path path = new Path();
        path.moveTo(300, 1200);
        path.lineTo(300, 1410);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        GestureDescription gesture = builder
                .addStroke(new GestureDescription.StrokeDescription(path, 50, 100))
                .build();
        this.dispatchGesture(gesture, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.i(TAG, "onCompleted: 滑动Down，手势完成");
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.i(TAG, "onCancelled: 失败");
            }
        }, null);
    }

    private void click(final float x, final float y) {  //模拟手势按位置点击
        Path path = new Path();
        path.moveTo(x, y);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        GestureDescription gesture = builder
                .addStroke(new GestureDescription.StrokeDescription(path, 50, 100))
                .build();
        this.dispatchGesture(gesture, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.i(TAG, "onCompleted: 手势完成 x:"+x +" y:" + y);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.i(TAG, "onCancelled: 失败");
            }
        }, null);
    }

    private List<AccessibilityNodeInfo> mListNodeInfo = new ArrayList<>();
    public AccessibilityNodeInfo findAllTextInNodeInfo(AccessibilityNodeInfo node, String text, int type) {
        AccessibilityNodeInfo temp;
        if (node.getChildCount() == 0) {
            if (node.getText() != null) {
                if(type == 0){
                    if (text.equals(node.getText().toString())) {
                        return node;
                    }
                }else if(type == 1){
                    if (node.getText().toString().contains(text)) {
                        return node;
                    }
                }else if(type == 2){
                    if (node.getText().toString().matches(text)) {
                        return node;
                    }
                }
            }
        } else {
            for (int i = 0; i < node.getChildCount(); i++) {
                if (node.getChild(i) != null) {
                    temp = findAllTextInNodeInfo(node.getChild(i), text, type);
                    if(temp != null){
                        mListNodeInfo.add(temp);
                    }
                }
            }
        }
        return null;
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        Log.d(TAG, event.getPackageName() + " " + event.getEventType() + " " + event.getContentDescription() + " " + event.getClassName());

        AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();

        if(rootInActiveWindow == null){
            Log.d(TAG, "rootInActiveWindow == null, return");
            return;
        }

//        String className = event.getClassName().toString();
//        if(className != null && className.contains("SystemDashboard")){
//            Log.d(TAG, "onAccessibilityEvent check SystemDashboard, back");
//            performGlobalAction(GLOBAL_ACTION_BACK);
//        }

    }

    @Override
    protected boolean onKeyEvent(KeyEvent event) {
        Log.d(TAG, "onKeyEvent keycode = " + event.getKeyCode());
        int key = event.getKeyCode();
        switch (key) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                Log.d(TAG, "KEYCODE_VOLUME_DOWN");
                pause();
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                Log.d(TAG, "KEYCODE_VOLUME_UP");
                break;
        }
        return super.onKeyEvent(event);
    }

    @Override
    public void onInterrupt() {
        Log.e(TAG, "onInterrupt");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(heartBeatTimer != null){
            heartBeatTimer.cancel();
        }

        if(accessibilityTimer != null){
            accessibilityTimer.cancel();
        }

        mHandler.removeCallbacks(sRunnable);

        vibrator = null;

        if (null != mWakeLock) {
            mWakeLock.release();
            mWakeLock = null;
        }

        Log.e(TAG, "onDestroy in AccessibilityService");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.e(TAG, "onRebind");
        super.onRebind(intent);
    }

    private WindowManager windowManager ;
    private WindowManager.LayoutParams layoutParams;
    private Button button;

    private void showFloatingWindow() {
        if (Settings.canDrawOverlays(this)) {
            // 获取WindowManager服务
            windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

            // 新建悬浮窗控件
            button = new MyButton(getApplicationContext());
            button.setText("");
            button.setBackgroundColor(Color.TRANSPARENT);
            //button.setBackgroundColor(Color.BLUE);

            //button.setOnTouchListener(new FloatingOnTouchListener());

            // 设置LayoutParam
            layoutParams = new WindowManager.LayoutParams();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
            layoutParams.flags=WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN|WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
            layoutParams.format = PixelFormat.RGBA_8888;
            layoutParams.width = 800;
            layoutParams.height = 50;
            layoutParams.x = 0;
            layoutParams.y = -1000;

            // 将悬浮窗控件添加到WindowManager
            windowManager.addView(button, layoutParams);
        }else{
            Toast.makeText(this, "当前无权限，请授权", Toast.LENGTH_SHORT);
            startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())));
        }
    }

    private class MyButton extends  android.support.v7.widget.AppCompatButton{

        public MyButton(Context context) {
            super(context);
        }

        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            Log.e(TAG, "dispatchKeyEvent " + event);
            return super.dispatchKeyEvent(event);
        }
    }

    private class FloatingOnTouchListener implements View.OnTouchListener {
        private int x;
        private int y;

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    x = (int) event.getRawX();
                    y = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - x;
                    int movedY = nowY - y;
                    x = nowX;
                    y = nowY;
                    layoutParams.x = layoutParams.x + movedX;
                    layoutParams.y = layoutParams.y + movedY;

                    // 更新悬浮窗控件布局
                    windowManager.updateViewLayout(view, layoutParams);
                    break;
                default:
                    break;
            }
            return false;
        }
    }

    private void checkIsForbidSetting(){

        int dingState = 0;

        try {
            dingState = AppUtil.getDingState(getApplicationContext());
        }catch (Exception e){
            Log.e(TAG, e.toString());
        }

        Log.e(TAG, "checkIsForbidSetting dingState=" + dingState + " button="+button);

        if(dingState == 0 || dingState == 2){
            if(button != null) {
                try {
                    windowManager.removeView(button);
                    button = null;
                }catch (Exception e){
                    Log.e(TAG, e.toString());
                }
            }
        }else{
            if(button == null) {
                showFloatingWindow();
            }
        }
    }
}